﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Hosting;
using System.Web;
using System.Web.Caching;
using System.Collections;

namespace PaymentHelper.Core.ViewEmbeddedHandler
{
    public class EmbeddedViewVirtualPathProvider:VirtualPathProvider
    {
        private readonly EmbeddedViewCollection _embeddedViews;

        public EmbeddedViewVirtualPathProvider(EmbeddedViewCollection emCol)
        {
            if (emCol == null)
                throw new PaymentHelper.Core.ExceptionHandler.PaymentHelperException(ExceptionHandler.ExceptionLevel.Warning, "EmbeddedViewVirtualPathProvider", "Argument embeddedViewsCollection in contructor is null");
            
            this._embeddedViews = emCol;
        }

        private bool IsEmbeddedView(string virtualPath)
        {
            if (string.IsNullOrEmpty(virtualPath))
                return false;

            string virtualPathAppRelative = VirtualPathUtility.ToAppRelative(virtualPath);
            if (!virtualPathAppRelative.StartsWith("~/Views/", StringComparison.InvariantCultureIgnoreCase))
                return false;
            string viewName =  GetFullyQualifiedViewName(virtualPathAppRelative);

            return _embeddedViews.ContainsView(viewName);
        }

        private string GetFullyQualifiedViewName(string virtualPathAppRelative)
        {
            int lastPos = virtualPathAppRelative.LastIndexOf('/') ;
            int length = virtualPathAppRelative.Length - 1 - lastPos;
            return virtualPathAppRelative.Substring(lastPos + 1, length);
        }

        public override bool FileExists(string virtualPath)
        {
            return (IsEmbeddedView(virtualPath) || Previous.FileExists(virtualPath));
        }

        public override VirtualFile GetFile(string virtualPath)
        {
            if (IsEmbeddedView(virtualPath))
            {
                string virtualPathRelative = VirtualPathUtility.ToAppRelative(virtualPath);
                var viewName = GetFullyQualifiedViewName(virtualPathRelative);

                var embeddedViewData = _embeddedViews.FindView(viewName);
                return new EmbeddedResourceVirtualFile(embeddedViewData,virtualPath);
            }

            return Previous.GetFile(virtualPath);
        }

        public override CacheDependency GetCacheDependency(string virtualPath, IEnumerable virtualPathDependencies, DateTime utcStart)
        {
            return IsEmbeddedView(virtualPath) ? null : Previous.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
        }
    }
}
